package com.bt.framework.ext

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart

/**
 * @param total 倒计时总时长
 * @param scope 协程作用域
 * @param onTick 倒计时过程回调
 * @param onStart 倒计时开始时回调
 * @param onFinish 倒计时结束时回调
 */
fun countDownCoroutines(
    total: Int,
    scope: CoroutineScope,
    onTick: (Int) -> Unit,
    onStart: (() -> Unit)? = null,
    onFinish: (() -> Unit)? = null
): Job {
    return flow {
        for (i in total downTo 0) {
            emit(i)
            delay(1000)
        }
    }
        .flowOn(Dispatchers.Main)
        .onStart { onStart?.invoke() }
        .onEach { onTick.invoke(it) }
        .onCompletion { onFinish?.invoke() }
        .launchIn(scope)
}